<template>
  <div class="app-container">
    <h1>教师信息列表</h1>
    <el-divider/>

    <el-form :inline="true" :model="teacherQuery" class="demo-form-inline">
      <el-form-item label="工号">
        <el-input v-model="teacherQuery.noId" placeholder="工号"/>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="teacherQuery.name" placeholder="姓名"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getTeacherList">查询</el-button>
      </el-form-item>
    </el-form>

    <el-divider/>

    <el-button-group>
      <el-button type="primary" size="small" @click="handleImportTeacher">
        <svg-icon icon-class="import"/>
        导入教师
      </el-button>
      <el-button type="success" size="small" @click="handleAddTeacher">
        <svg-icon icon-class="add"/>
        添加教师
      </el-button>
      <el-popconfirm
        title="确定删除选中教师么？"
        icon-color="red"
        icon="el-icon-info"
        @confirm="submitDeleteTeachers"
      >
        <el-button slot="reference" :disabled="isDisabled" type="danger" size="small">
          <svg-icon icon-class="remove"/>
          删除选中教师
        </el-button>
      </el-popconfirm>
    </el-button-group>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="数据加载中"
      stripe
      border
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55"/>
      <el-table-column
        prop="name"
        fixed="left"
        label="姓名"/>
      <el-table-column
        prop="noId"
        label="工号"/>
      <el-table-column
        :formatter="handGender"
        prop="gender"
        label="性别"/>
      <el-table-column
        prop="mobile"
        label="手机号"/>
      <el-table-column
        prop="email"
        label="邮箱"/>
      <el-table-column
        prop="address"
        label="地址"/>
      <el-table-column fixed="right" label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="getTeacherInfo(scope.row.id)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <br>
    <div class="block">
      <el-pagination
        :current-page="page"
        :page-sizes="[5, 10, 15, 30, 50, 100]"
        :page-size="pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="changSize"
        @current-change="changePage"/>
    </div>

    <el-dialog :close-on-click-modal="false" :visible.sync="teacherInfoFlag" title="详细信息">
      <el-form ref="teacherInfo" :model="teacherInfo" label-width="100px">
        <el-form-item
          :rules="[
            { required: true, message: '请输入教师姓名', trigger: 'blur' }
          ]"
          prop="name"
          label="姓名">
          <el-input v-model="teacherInfo.name"/>
        </el-form-item>
        <el-form-item
          :rules="[
            { required: true, message: '请输入教师工号', trigger: 'blur' }
          ]"
          prop="noId"
          label="工号">
          <el-input v-model="teacherInfo.noId"/>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="teacherInfo.gender">
            <el-radio label="0">女</el-radio>
            <el-radio label="1">男</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          :rules="[
            { required: false },
            { validator: mobileRule, message: '请输入正确的11位手机号', trigger: 'blur' }
          ]"
          prop="mobile"
          label="手机号"
        >
          <el-input v-model="teacherInfo.mobile"/>
        </el-form-item>
        <el-form-item
          :rules="[
            { required: false },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
          ]"
          prop="email"
          label="邮箱"
        >
          <el-input v-model="teacherInfo.email"/>
        </el-form-item>
        <el-form-item label="住址">
          <el-input v-model="teacherInfo.address"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-popconfirm
          title="确定重置教师密码么？（默认密码：123456）"
          @confirm="resetPassword"
        >
          <el-button slot="reference" type="primary">重置密码</el-button>
        </el-popconfirm>
        <el-button type="success" @click="submitUpdate('teacherInfo')">保存修改</el-button>
        <el-popconfirm
          title="确定删除此教师么？"
          icon-color="red"
          icon="el-icon-info"
          @confirm="submitDelete"
        >
          <el-button slot="reference" type="danger">删除教师</el-button>
        </el-popconfirm>
        <el-button type="info" @click="teacherInfoFlag = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" :visible.sync="importTeacherFlag" title="导入教师">
      <el-upload
        ref="upload"
        :file-list="fileList"
        :on-change="handleChange"
        :action="uploadUrl"
        :show-file-list="true"
        :on-success="onSuccess"
        :on-error="onError"
        :auto-upload="false"
        :headers="myHeader"
        class="upload-demo"
        accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      >
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件，且不超过500kb。注意上传文件格式，详情可见
          <router-link to="/admin/help/teacher">
            <el-link :underline="false" type="success">帮助文档</el-link>
          </router-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitImport">导入</el-button>
        <el-button type="info" @click="importTeacherFlag = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" :visible.sync="addTeacherFlag" title="添加教师">
      <el-form ref="addTeacher" :model="addTeacher" label-width="100px">
        <el-form-item
          :rules="[
            { required: true, message: '请输入教师姓名', trigger: 'blur' }
          ]"
          prop="name"
          label="姓名">
          <el-input v-model="addTeacher.name"/>
        </el-form-item>
        <el-form-item
          :rules="[
            { required: true, message: '请输入教师工号', trigger: 'blur' }
          ]"
          prop="noId"
          label="工号">
          <el-input v-model="addTeacher.noId"/>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="addTeacher.gender">
            <el-radio label="0">女</el-radio>
            <el-radio label="1">男</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          :rules="[
            { required: false },
            { validator: mobileRule, message: '请输入正确的11位手机号', trigger: 'blur' }
          ]"
          prop="mobile"
          label="手机号"
        >
          <el-input v-model="addTeacher.mobile"/>
        </el-form-item>
        <el-form-item
          :rules="[
            { required: false },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
          ]"
          prop="email"
          label="邮箱"
        >
          <el-input v-model="addTeacher.email"/>
        </el-form-item>
        <el-form-item label="住址">
          <el-input v-model="addTeacher.address"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddTeacher('addTeacher')">添加</el-button>
        <el-button type="info" @click="addTeacherFlag = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import teacherApi from '@/api/admin/teacher'
import store from '../../../store'

export default {
  data() {
    return {
      list: null,
      listLoading: true,
      page: 1,
      total: 0,
      pageSize: 10,
      LabelWidth: '120px',
      isDisabled: true,
      multipleSelection: [],

      teacherQuery: {
        page: 1,
        limit: 10,
        noId: null,
        name: null
      },
      teacherInfoFlag: false,
      teacherInfo: {},

      importTeacherFlag: false,

      addTeacherFlag: false,
      addTeacher: {
        name: '',
        noId: '',
        clazzId: '',
        gender: '0',
        mobile: '',
        email: '',
        address: ''
      },

      fileList: [],
      uploadUrl: 'http://localhost:8000/score/api/admin/teacher/import',
      myHeader: {
        Authorization: store.getters.token
      }
    }
  },
  created() {
    this.getTeacherList()
  },
  methods: {
    getTeacherList() {
      this.listLoading = true
      this.teacherQuery.page = this.page
      this.teacherQuery.limit = this.pageSize
      teacherApi.queryTeachers(this.teacherQuery).then(res => {
        this.listLoading = false
        this.total = Number.parseInt(res.result.counts)
        this.list = res.result.items
      }).catch(error => {
        console.log(error)
      })
    },
    handGender(teacher) {
      if (teacher.gender === '0') {
        return '女'
      }
      return '男'
    },
    changSize(pageSize) {
      this.pageSize = pageSize
      this.getTeacherList()
    },
    changePage(page) {
      this.page = page
      this.getTeacherList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map(teacher => teacher.id)
      this.isDisabled = this.multipleSelection.length === 0
    },
    getTeacherInfo(id) {
      teacherApi.queryTeacher(id).then(res => {
        this.teacherInfo = res.result
        this.teacherInfoFlag = true
      }).catch(error => {
        console.log(error)
      })
    },
    mobileRule(rule, value, callback) {
      if (value !== null && value.length !== 0 && !/^1(3|4|5|6|7|8)\d{9}$/.test(value)) {
        return callback(new Error('请输入正确的11位手机号'))
      }
      return callback()
    },
    resetPassword() {
      teacherApi.resetPassword(this.teacherInfo.id).then(res => {
        this.$message({
          message: '重置密码成功',
          type: 'success'
        })
      }).catch(error => {
        console.log(error)
      })
    },
    submitUpdate(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.teacherInfo.clazzId = this.teacherInfo.clazz
          teacherApi.updateTeacher(this.teacherInfo).then(res => {
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            this.teacherInfoFlag = false
            this.getTeacherList()
          }).catch(error => {
            console.log(error)
          })
        } else {
          this.$message({
            message: '请按规则完善信息',
            type: 'warning'
          })
          return false
        }
      })
    },
    submitDelete() {
      teacherApi.deleteTeacher(this.teacherInfo.id).then(res => {
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.teacherInfoFlag = false
        this.multipleSelection = []
        this.getTeacherList()
      }).catch(error => {
        console.log(error)
      })
    },
    submitDeleteTeachers() {
      teacherApi.deleteTeachers(this.multipleSelection).then(res => {
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.multipleSelection = []
        this.getTeacherList()
      }).catch(error => {
        console.log(error)
      })
    },
    handleImportTeacher() {
      this.importTeacherFlag = true
    },
    handleAddTeacher() {
      this.addTeacherFlag = true
      this.addTeacher = {
        name: '',
        noId: '',
        clazzId: '',
        gender: '0',
        mobile: '',
        email: '',
        address: ''
      }
    },
    submitAddTeacher(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          teacherApi.addTeacher(this.addTeacher).then(res => {
            this.$message({
              message: '添加成功',
              type: 'success'
            })
            this.addTeacherFlag = false
            this.getTeacherList()
          }).catch(error => {
            console.log(error)
          })
        } else {
          this.$message({
            message: '请按规则完善信息',
            type: 'warning'
          })
          return false
        }
      })
    },
    onSuccess(res) {
      this.$message({
        message: '导入成功',
        type: 'success'
      })
      this.fileList = []
      this.importTeacherFlag = false
      this.getTeacherList()
    },
    onError(res) {
      this.$message({
        message: '导入失败，请重试',
        type: 'error'
      })
      this.fileList = []
      this.importTeacherFlag = false
    },
    handleChange(file, fileList) {
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]] // 这一步，是 展示最后一次选择的csv文件
      }
    },
    submitImport() {
      this.$refs.upload.submit()
    }
  }
}
</script>
